import AppUtil from "../../framework/scripts/AppUtil"
import Singleton from "../../framework/scripts/base/Singleton"
import EventMgr from "../../framework/scripts/manager/EventMgr"
import ResMgr from "../../framework/scripts/manager/ResMgr"
import GameConstants from "../GameConstants"


export default class ResCacheMgr extends Singleton {
    public static get inst() {
        return this.getInstance<ResCacheMgr>()
    }

    constructor() {
        super()

        this.init()
    }


    private _audios: Map<string, cc.AudioClip> = new Map()

    public getAudio(audioName: string): cc.AudioClip {
        return this._audios.get(audioName)
    }


    private async init() {
        let res = await this.initAudio()
        if (!res) return

        EventMgr.emit(GameConstants.event.ResCacheLoadOk)
    }

    private async initAudio() {
        const [audios, error] = await AppUtil.asyncWrap<cc.AudioClip[]>(ResMgr.loadResDir('audio'))
        if (error) {
            cc.error(`ResCacheMgr.initAudio error:${error}`)
            return false
        }

        audios.forEach((audio) => this._audios.set(audio.name, audio))

        return true
    }
}
